﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Sharp.Domain.PlatformBoundedContext
{
    public class MyConfiguration : DbConfiguration
    {
        public MyConfiguration() : base()
        {
            var directoryName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "App_Data";
            if (!Directory.Exists(directoryName))
            {
                directoryName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            }

            MyDbModelStore cachedDbModelStore = new MyDbModelStore(directoryName);
            this.SetModelStore(cachedDbModelStore);
        }

    }
    class MyDbModelStore : DefaultDbModelStore
    {
        public MyDbModelStore(string location)
            : base(location)
        { }
        
        public override DbCompiledModel TryLoad(Type contextType)
        {
            string path = GetFilePath(contextType);
            if (File.Exists(path))
            {
                DateTime lastWriteTime = File.GetLastWriteTimeUtc(path);
                DateTime lastWriteTimeDomainAssembly = File.GetLastWriteTimeUtc(typeof(Entities).Assembly.Location);
                if (lastWriteTimeDomainAssembly > lastWriteTime)
                {
                    File.Delete(path);
                    //Tracers.EntityFramework.TraceInformation("Cached db model obsolete. Re-creating cached db model edmx.");
                }
            }

            return base.TryLoad(contextType);
        }

        // 6.2 有bug，contextType.Assembly.Location 为空
        //protected override bool FileIsValid(Type contextType, string filePath)
        //{
        //    var contextCreated =
        //        File.GetLastWriteTimeUtc(contextType.Assembly.CodeBase.Replace("file://", ""));
        //    var storeCreated = File.GetLastWriteTimeUtc(filePath);
        //    return storeCreated >= contextCreated;
        //}
    }
}